[all_opts,use_libigl_static_library] = gptoolbox_mexopts();

libigl_libs = cellfun( ...
  @(s) strrep(s,'-l',''), ...
  all_opts(cellfun(@(s) startsWith(s,'-ligl'),all_opts)), ...
  'UniformOutput',false);
warning([ ...
  'This is **VERY** experimental. In principle, this should compile all ', ...
  'of the mex functions in this directory. In practice, users will ', ...
  'surely have to adjust paths and flags at the top of this file.']);
input('Hit any key to continue...');

out_of_date = @(prefix) ...
  ~exist(['./' prefix '.mexmaci64'],'file') || ...
  (datenum(getfield(dir([prefix '.cpp']),'date')) > ...
  datenum(getfield(dir([prefix '.mexmaci64']),'date'))) ||  ...
  (use_libigl_static_library  &&  ...
  any(cellfun( ...
    @(s) datenum(getfield(dir([path_to_libigl,'/lib/lib' s '.a']),'date')) > ...
    datenum(getfield(dir([prefix,'.mexmaci64']),'date')),libigl_libs)));

prefixes = { ...
  'ambient_occlusion', ...
  'bone_visible', ...
  'bone_visible_embree', ...
  'collapse_small_triangles', ...
  'decimate_cgal', ...
  'decimate_libigl', ...
  'eltopo', ...
  'fit_rotations_mex', ...
  'in_element_aabb', ...
  'intersect_other', ...
  'mesh_boolean', ...
  'outer_hull', ...
  'point_mesh_squared_distance', ...
  'ray_mesh_intersect', ...
  'read_mesh_from_xml', ...
  'reorient_facets', ...
  'selfintersect', ...
  'segment_graph', ...
  'signed_distance', ...
  'signed_distance_isosurface', ...
  'simplify_polyhedron', ...
  'slim', ...
  'solid_angle', ...
  'trim_with_solid', ...
  'winding_number', ...
  'wire_mesh' };

errors = '';
for prefix = prefixes
  prefix = prefix{1};
  if out_of_date(prefix)
    fprintf('============== %s ==============\n',prefix);
    try
      mex( all_opts{:}, [prefix '.cpp']);
    catch ME
      fprintf('----- Error (see `errors`) -----\n');
      warning(ME.identifier,ME.message);
      errors = [errors ME.message];
    end
  end
end

% ONE-OFFs

% impaste is currently only implemented for mac
if ismac
  try
    fprintf('============== %s ==============\n','impaste');
    mex(all_opts{:}, '-output','impaste','impaste.cpp','paste.mm');
  catch ME
    fprintf('----- Error (see `errors`) -----\n');
    warning(ME.identifier,ME.message);
    errors = [errors ME.message];
  end
end

